<template>
  <div>
    <div class="flexrowbetween flexwrapper" style="align-items: flex-start">
      <div class="flex aligncenter">
        <div
          class="iconbox flexcenter commhover blackbg mr_15"
          @click="resetQuery"
        >
          <i class="el-icon-refresh f-20" :class="{ rotate: isrefresh }"></i>
        </div>
        <el-button type="primary" plain size="small" :disabled='multiple' @click="openDraw">指定中奖</el-button>
        <el-button type="primary" plain size="small" @click="handleFabu">预览</el-button>
        <div>【{{ row.name || row.t_name }}】的用户列表</div>
      </div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="0"
      >
        <el-form-item prop="keyword">
          <el-input
            class="searchinput"
            v-model="queryParams.keyword"
            placeholder="请输入名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item>
          <el-dropdown trigger="click" @command="handleCommand">
            <el-button size="mini" class="nol_border plr_9">
              <svg-icon class-name="f-14" icon-class="export" />
              <i class="el-icon-caret-bottom el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in exportlist"
                :key="index"
                :command="item.id"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item> -->
        <el-form-item>
          <el-button
            class="f-14"
            type=""
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          ></el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      ref="tablelayout"
      class="commtable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" prop="id" align="center" width="80" />
      <el-table-column label="奖项类型" prop="platName" align="center">
        <template slot-scope="scope"> 
          <div v-if="scope.row.taskdraw">
            <span v-if="scope.row.taskdraw.type==1">虚拟卡券</span>
            <span v-if="scope.row.taskdraw.type==2">实物奖励</span>
            <span v-if="scope.row.taskdraw.type==3">多抽x次</span>
            <span v-if="scope.row.taskdraw.type==5">现金红包</span>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="奖项名称" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.taskdraw.draw_name || '-'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否已指定"
          align="center"
        >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_zd"
            active-color="#13ce66"
            inactive-color="#eee"
            :inactive-value="0"
            :active-value="1"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="是否已抽奖"
          align="center"
        >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_cj"
            active-color="#13ce66"
            inactive-color="#eee"
            :inactive-value="0"
            :active-value="1"
            disabled
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="兑奖码" prop="code" align="center" /> -->
      <el-table-column
        prop="created_at"
        label="操作"
        width="150"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <div class="flex btnflex">
            <div
              class="commhover btn_blue mr_10 c_fff"
              @click="handleEdit(scope.row)"
            >
              编辑
            </div>
            <div v-if="scope.row.m_id !== 0" class="commhover btn_yellow c_fff mr_10"
              @click="handleDelete(scope.row)">
              删除
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.num"
      @pagination="getList"
    />
    <el-dialog
      title="预览"
      :visible.sync="dialogVisible"
      width="680px"
      class="dialogheaderbg"
      :before-close="handleClose"
      :close-on-click-modal='false'
      append-to-body
    >
      <el-table
        v-loading="ylloading"
        :data="yltableData"
        border
        ref="tablelayout"
        class="commtable"
      >
        <el-table-column label="指定奖项" prop="platName" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.taskdraw.level_name || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="指定奖品" prop="taskdraw.draw_name" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.taskdraw.draw_name || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.wxuser.photo" :src="scope.row.wxuser.photo" alt="" class="imgmini">
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="wxuser.name" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.wxuser.name || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否已开奖" prop="code" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.num==0">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="yltotal > 0"
        :total="yltotal"
        :page.sync="ylqueryParams.page"
        :limit.sync="ylqueryParams.num"
        @pagination="getYlTable"
      />
      <!-- <time-yulan v-if="dialogVisible" :rowid="row.id" @close="handleClose" /> -->
    </el-dialog>

    <!-- 指定开奖 -->
    <el-dialog
      class="dialogheaderbg"
      :title="title"
      :visible.sync="open"
      width="680px"
      append-to-body	
      :before-close="handleCloseOpen"
      :close-on-click-modal='false'>
      <el-form v-if="open" :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
        <el-form-item label="ID：" prop="pool_id">
          <el-input v-model="form.pool_id" placeholder="ID" readonly />
          <!-- <el-select v-model="form.code_id" multiple placeholder="请选择用户">
            <el-option v-for="(item,index) in rowids" :key="index" :label="item.code" :value="item.id" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="指定中奖：" prop="status">
          <el-switch v-model="form.status" :inactive-value="0" :active-value="1" disabled></el-switch>
        </el-form-item>
        <el-form-item label="用户：" prop="wx_id">
          <el-select v-model="form.wx_id" placeholder="请选择用户" remote filterable :remote-method="remoteMethod" :loading="loadingsearch" style="width:100%">
            <el-option v-for="(item,index) in userlist" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" prop="remak">
          <el-input v-model="form.remak" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCloseOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { timeDrawIndex,timeDrawList,timeDraw,drawList } from "@/api/active";
import {drawPoolIndex, wxuserList, poolDrawList, poolDraw, drawPoolDel,drawPoolUserIndex} from '@/api/sethome'
import TimeYulan from './TimeYulan.vue'
import { getMemberToken } from "@/api/member";

export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
        id: "",
        keyword: undefined,
      },
      total: 1,
      loading: false,
      rowids: [],
      multiple: true,
      tableData: [],
      isrefresh: false,
      dialogVisible: false,

      // 日志
      dialoglogVisible: false,
      rowId: "",

      // 预览
      dialogView: false,
      timeopen: false,

      codeList:[],
      drawList:[],
      open:false,
      title:'',
      form:{
        task_id:'',
        pool_id:[],
        status:1,
        wx_id:'',
        msg:''
      },
      rules:{
        wx_id:[{ required: true, message: '请选择用户', trigger: 'change' }],
        pool_id:[{ required: true, message: '请选择奖项', trigger: 'change' }],
        task_id:[{ required: true, message: '请选择任务', trigger: 'change' }],
      },
      typeOpen:'',
      myrow:null,
      userlist:[],
      loadingsearch: false,
      ylloading:false,
      yltableData:[],
      yltotal:0,
      ylqueryParams:{
        page:1,
        num: 10,
        id:''
      },
    };
  },

  props: {
    type: {
      type: Number,
      default: 1,
    },
    row: {
      type: Object,
      default: {},
    },
  },

  components:{
    TimeYulan
  },

  created() {
    if(this.type == 1){
      this.queryParams.id = this.row.id;
    }else{
      this.queryParams.id = this.row.t_id;
    }
    this.getList();
    // this.getUserList()
  },

  methods: {

    changeUser(val){
      console.log('val:', val)
      if(val){
        wxuserList({id:this.queryParams.id,keyword:this.form.wx_id}).then(res=>{
          this.userlist = res.data
        })
      }
    },

    remoteMethod(query,wxid='') {
      console.log('query：',query,wxid)
      if (query !== '') {
        this.loadingsearch = true;
        // setTimeout(() => {
        //   this.loading = false;
        //   this.options = this.list.filter(item => {
        //     return item.label.toLowerCase()
        //       .indexOf(query.toLowerCase()) > -1;
        //   });
        // }, 200);
        wxuserList({id:this.queryParams.id,keyword:query}).then(res=>{
          this.userlist = res.data
          console.log('this.userlist：', this.userlist)
          this.loadingsearch = false;
          if(wxid){
            // console.log(typeof wxid)
            this.$nextTick(()=>{
              this.form.wx_id = wxid
            })
          }
        })
      } else {
        this.userlist = [];
      }
    },



    getList() {
      this.loading = true;
      let params = {
        page: this.queryParams.page,
        num: this.queryParams.num,
        id: this.queryParams.id,
      };
      if (this.queryParams.keyword) {
        params.keyword = this.queryParams.keyword;
      }
      drawPoolIndex(params).then((response) => {
        this.tableData = response.data.list.map(item=>{
          item.is_zd=item.m_id==0?0:1;
          item.is_cj=item.num==0?1:0;
          return item
        });
        this.total = response.data.count;
        this.loading = false;
        this.isrefresh = false;
      });
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.isrefresh = true;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.rowids = selection.map((item) => ({id:item.id,code:item.code}));
      this.multiple = !selection.length;
    },

    getDrawList(){
      drawList({id:this.queryParams.id}).then(res=>{
        this.drawList = res.data
      })
    },

    openDraw(){
      // this.getDrawList()
      this.title = '批量指定中奖'
      this.typeOpen = 1
      this.form.task_id = this.queryParams.id
      this.form.pool_id = this.rowids.map(item=>item.id)
      // this.form.code_id = this.rowids.map(item=>item.id)
      // this.form.id = this.row.id
      // this.form.level = 1
      this.open = true
    },

    handleCloseOpen(){
      this.open = false
    },

    handleEdit(row) {
      console.log('row:', row)
      // this.getDrawList()
      if(row.wxuser){
        this.remoteMethod(row.wxuser.name,row.wxuser.id)
      }
      this.title = '编辑开奖设置'
      this.typeOpen = 2
      this.myrow = row
      this.form.task_id = this.queryParams.id
      this.form.pool_id = this.myrow.id
      // this.form.wx_id = row.wxuser?row.wxuser.id:''
      this.open = true
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const infoIds = row.id;
      this.$modal.confirm('是否确认删除编号为"' + infoIds + '"的数据项？').then(() => {
        return drawPoolDel({pool_id:infoIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    submitForm(){
      this.$refs.form.validate(valid=>{
        if(!valid) return
        if(this.typeOpen == 1){
          poolDrawList(this.form).then(res=>{
            this.$message.success('设置成功')
            this.handleCloseOpen()
            this.getList();
          })
        }else{
          let params = {
            task_id:this.form.task_id,
            pool_id:this.myrow.id,
            wx_id: this.form.wx_id
          }
          poolDraw(params).then(()=>{
            this.$message.success('设置成功')
            this.handleCloseOpen()
            this.getList();
          })
        }
        
      })
    },

    handleCommand(command) {
      console.log(command);
    },

    handleFabu() {
      this.ylqueryParams.id = this.queryParams.id
      this.dialogVisible = true;
      this.getYlTable()
    },

    getYlTable(){
      this.ylloading = true
      drawPoolUserIndex(this.ylqueryParams).then(res=>{
        // console.log()
        this.ylloading = false
        this.yltableData = res.data.list
        this.yltotal = res.data.count
      }).catch(()=>{
        this.ylloading = false
      })
    },

    handleClose() {
      this.dialogVisible = false;
    },

    handleLog(row) {
      this.rowId = row.id;
      this.dialoglogVisible = true;
    },

    handleLogClose() {
      this.dialoglogVisible = false;
    },

    // 预览
    handleDetail(row) {
      this.rowId = row.id;
      this.dialogView = true;
    },

    handleViewClose() {
      this.dialogView = false;
    },

    handleOpenTime(row) {
      this.rowId = row.id;
      this.timeopen = true;
    },

    handleCloseTime() {
      this.timeopen = false;
    },
    

    // 删除
    handleDetele(row) {
      this.$confirm("确定删除该条的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          btnDelete({
            id: row.id,
          }).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.iconbox {
  width: 32px;
  height: 26px;
}
.imgmini {
  width: 40px;
  height: 40px;
  margin: auto;
}
.imgbox {
  width: 120px;
  height: 120px;
}
</style>
